const mysql = require('mysql');
const GenId = require('../utils/snowFlake')

const db = mysql.createPool({
  host: '127.0.0.1',
  user: 'root',
  password: 'MySQL666',
  database: 'blog_db'
})
const genid = new GenId({ WorkerId: 1 })

db.async = (sqlStr) => {
  return new Promise((resolve, reject) => {
    db.query(sqlStr, (err, results) => {
      if (err) {
        reject(err);
      }
      if ((!results || results.length <= 0) && (!results || results.affectedRows !== 1)) {
        reject('数据库操作失败！')
      }
      resolve(results);
    })
  }).then((results) => {
    return new Promise((resolve, reject) => {
      resolve(results)
    })
  }, (response) => {
    return new Promise((resolve, reject) => {
      reject({ err: response })
    })
  }).catch((err) => {
    return err
  })
}

module.exports = { db, genid };